import 'dart:async';

import 'package:flutter/material.dart';
import 'package:splash_login/common/app_color.dart';
import 'package:splash_login/common/assets.dart';
import 'package:splash_login/pages/welcome.dart';

class SplashPage extends StatefulWidget {
  const SplashPage({super.key});

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  // 计数变量
  final duration = 10;
  int num = 0;

  // 倒计时的函数
  Future<void> _countdown() async {
    num = duration;
    for (var i = 0; i < duration; i++) {
      await Future.delayed(const Duration(seconds: 1), () {
        if (mounted == true) {
          setState(() {
            num--;
          });
        }
      });

      if (num == 0) {
        print('倒计时结束');
        Navigator.pushReplacement(context,
            MaterialPageRoute(builder: (context) => const WelcomePage()));
      }
    }
  }

  // Logo
  Widget _buildLogo() {
    return Stack(alignment: Alignment.center, children: [
      Container(
        // 底部
        // color: Colors.white,
        width: 120,
        height: 120,
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(120 / 2)),
      ),
      // 图片
      Image.asset(
        AssetsImages.logoPng,
        width: 84,
        height: 80,
      )
    ]);
  }

  // 文字显示
  Text _buildText(String text) {
    return Text(
      text,
      style: const TextStyle(
          fontSize: 19,
          // fontFamily: 'Poppins',
          fontWeight: FontWeight.bold,
          color: Colors.white,
          height: 22 / 19),
    );
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // logo
          _buildLogo(),
          const SizedBox(
            height: 24,
          ),
          // 标题
          _buildText("Online Market"),
          const SizedBox(
            height: 27,
          ),
          // 计数器
          _buildText(num > 0 ? "$num" : "Done")
        ],
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _countdown();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.bgSplash,
      body: _buildView(context),
    );
  }
}
